<?php
namespace Home\Controller;
use Think\Controller;
class UserController extends Controller {
    public function index(){
      //获取好友申请，留言记录，图片总数，好友数量
      $list['count_friend_apply'] = D('friend_apply')->where('b_user_id ='.$_SESSION['users']['user_id'].' and state = 0')->count();
      if(!$list['count_friend_apply']){$list['count_friend_apply']=0;}
      $list['count_message'] =D('message')->where('b_user_id ='.$_SESSION['users']['user_id'])->count();
      if(!$list['count_message']){$list['count_message']=0;}
      $list['count_img'] =D('img')->where('user_id='.$_SESSION['users']['user_id'])->count();
      if(!$list['count_img']){$list['count_img']=0;}
      $list['count_friend'] = D('friend')->where('user_id='.$_SESSION['users']['user_id'])->count();
      if(!$list['count_friend']){$list['count_friend']=0;}
    $this->assign('list',$list);
    $this->display('index');
}

//获取验证码
public function get_code(){
   echo  getCode(100,34);
}
  
   //登录验证  
    public function checkLogin(){
      if($_POST){
           $userModel=D('Users');
           $map['user_name']=$_POST['username'];
           $user = $userModel->where("user_name = '".$_POST['username']."'")->field('salt')->find();
           if(empty($user['salt'])){
            $this->error('登陆失败!');
           }
           $num = $_POST['password'].$user['salt'];
           $password = sha1($num);
            $res= $userModel->where("user_pwd = '".$password."'")->find();
            
            if(isset($res)){
                session('users',$res);
                $this->redirect('Index/index');
            }else{
              $this->error('用户名或密码错误!');
            }
      }else{
        $this->error('非法访问!');
      }
    } 
    
   //修改密码
    public function news_password(){
     extract($_POST);
    if(empty($password ) || empty($repassword)){
         echo json_encode(array("status"=>"0","msg"=>"密码或密码确认不能为空!"));
          exit;
     }
     if($password != $repassword){
         echo json_encode(array("status"=>"0","msg"=>"输入的密码不一致!"));
          exit;
     }
     if($code != $_SESSION['code']){
          echo json_encode(array("status"=>"0","msg"=>"验证码不正确!"));
          exit;
     }
      $user_id = $_SESSION['users']['user_id'];
      $data['salt'] =$salt= mt_rand(1000,9999);
      $num = $password.$salt;
      $data['user_pwd'] = sha1($num);
      $res = D('Users')->where('user_id = '.$user_id)->save($data);
      if($res){
          echo json_encode(array("status"=>"1","msg"=>"修改成功!"));
          exit;
      }else{
          echo json_encode(array("status"=>"0","msg"=>"修改失败!"));
          exit;
      }

    }

    //获取个人设置右边的html
    public function right_html(){
      extract($_REQUEST);
      $data = empty($data)?"":$data;
      $title = empty($data)?"":$title;
      $user = $_SESSION['users'];
      $userdata = D('Users')->where('user_id ='.$user['user_id'])->find();
      if($data == false){
          $this->error('非法操作');
      }
      if($title == "set_up"){
        $this->assign('user',$userdata);
      }else if($title == "head_portrait"){
        $this->assign('user',$userdata);
      }else if($title == "my_friend"){
       $users = D('friend')->alias('a')->field('b.*')->where('a.user_id='.$_SESSION['users']['user_id'])->join('left join ki_users as b on a.f_id = b.user_id')->select();
       $this->assign('users',$users);
      }else if($title == "picture_wall"){
       $wall = D('Wall')->where('user_id = '.$user['user_id'])->select();
       $this->assign('wall',$wall);
      }else if($title == "upload_picture"){
       $img = D('Img')->where('user_id = '.$user['user_id'].' and zutu_id < 0')->order("img_time desc")->select();
       $this->assign('img',$img);
      }else if($title=="zutu"){
        $zutu = D('zutu')->where('user_id='.$user['user_id'])->order('zutu_id desc')->select();
        if($zutu){
          foreach ($zutu as $key => $value) {
            $img = D('img')->where('user_id ='.$value['user_id'].' and zutu_id='.$value['zutu_id'])->order('createtime desc')->find();
            if($img){
              $value['thumb_url'] = $img['thumb_url'];
              $value['url'] = $img['url'];
              $zutu[$key] = $value;
            }
          }
        }
         $this->assign('zutu',$zutu);
      }else if($title="friend_apply"){
         $friend_apply = D('friend_apply')->alias('a')->join('left join ki_users as b on a.s_user_id = b.user_id')->where('b_user_id='.$_SESSION['users']['user_id'])->order('a.createtime desc')->select();
         if($friend_apply){
          $this->assign('friend_apply',$friend_apply);
         }
         print_r($friend_apply);
         exit;
      }
       
      $this->assign('data',$data);
      $this->display("$title");
      
    }

    //修改各人資料
    public function save(){
        extract($_POST);
        $where['user_id'] = $_SESSION['users']['user_id'];
        if(trim($name)==""){
          echo json_encode(array("status"=>"0","msg"=>"用户名不能位空!"));
          exit;
        }
        if(strlen($name) >40 ){
          echo json_encode(array("status"=>"0","msg"=>"用户名过长!"));
          exit;
        }
        $namelist = D('Users')->where("user_name='".$name."' and user_id != ".$where['user_id'])->find();
        if(!empty($namelist) || isset($namellist)){
          echo json_encode(array("status"=>"0","msg"=>"用户名已存在!"));
          exit;
        }
        $res = "/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/";
        if(!preg_match($res,$email)){
          echo json_encode(array("status"=>"0","msg"=>"电子邮箱不正确!"));
          exit;
        }
          $emaillist = D('Users')->where("email='".$email."' and user_id !=".$where['user_id'])->find();
        if(!empty($emaillist) || isset($emaillist)){
          echo json_encode(array("status"=>"0","msg"=>"邮箱已存在!"));
          exit;
        } 
        if(trim($motto) == ""){
          echo json_encode(array("status"=>"0","msg"=>"内容不能位空!"));
          exit;
        }
        $data['user_name'] = $name;
        $data['email'] = $email;
        $data['motto'] = $motto;
        $res = D('Users')->where($where)->save($data);
        if($res != false){
          echo json_encode(array("status"=>"1","msg"=>"设置成功!"));
          exit;
        }else{
          echo json_encode(array("status"=>"0","msg"=>"没有修改!"));
          exit;
        }
    }


    //ajax  修改头像设置
    public function ajax_upload(){
       $upload = new \Think\Upload();// 实例化上传类
      $upload->maxSize = 3145728;
      $upload->rootPath = './Public/img/';
      $upload->savePath = '';
      $upload->saveName = array('uniqid','');
      $upload->exts     = array('jpg', 'gif', 'png', 'jpeg');
      $upload->autoSub  = true;
      $upload->subName  = array('date','Ymd');
       // 上传文件 
      $info   =   $upload->upload($_FILES);
      if(!$info) {// 上传错误提示错误信息
         $this->error($upload->getError());
      }else{// 上传成功 获取上传文件信息
         //保存缩略图
        $images = new \Think\Image();

           $images->open('./Public/img/'.$info['image_url']['savepath'].$info['image_url']['savename']);
           $newsavename = str_replace('.','_thumb.',$info['image_url']['savename']);
           $wid = 100;
           $hei = 100;
           $vvv = $images->thumb($wid, $hei,\Think\Image::IMAGE_THUMB_FIXED)->save('./Public/img/'.$info['image_url']['savepath'].$newsavename);
           $vv = $images->thumb($wid, $hei,\Think\Image::IMAGE_THUMB_FIXED)->save('./Public/img/'.$info['image_url']['savepath'].$newsavename);
           $info['image_url']['savepath_thumb'] = "./Public/img/".$info['image_url']['savepath'];//缩略图显示路径
           $info['image_url']['savethumbname_thumb'] = $newsavename;
         foreach($info as $file){
             $imgurl= $file['savepath'].$file['savename'];
             $data['url'] = "img/".$imgurl;
             $data['thumb_url'] = "img/".$file['savepath'].$file['savethumbname_thumb'];
           }
           print_r($info);
         }
    }


//删除图片墙图片
    public function ajax_del_wall(){
      $id = empty($_POST['id'])?"":$_POST['id'];
      $res = D('Wall')->where('id='.$id)->delete();
      if($res){
          echo json_encode(array("status"=>"1","msg"=>"设置成功!"));
          exit;
        }else{
          echo json_encode(array("status"=>"0","msg"=>"删除成功!"));
          exit; 
        }

    }


 public function uploadify(){


     // $targetPath = "./Public/upload/";

    //echo $_POST['token'];
    $verifyToken = md5($_POST['timestamp']);

    if (!empty($_FILES) && $_POST['token'] == $verifyToken) {

      $upload = new \Think\Upload();// 实例化上传类
      $upload->maxSize = 3145728;
      $upload->rootPath = './Public/upload/';
      $upload->savePath = '';
      $upload->saveName = array('uniqid','');
      $upload->exts     = array('jpg', 'gif', 'png', 'jpeg');
      $upload->autoSub  = true;
      $upload->subName  = array('date','Ymd');
       // 上传文件 
      $info   =   $upload->upload($_FILES);
      //return false;
      if(!$info) {// 上传错误提示错误信息 
      echo $upload->getError();
      //echo $targetPath;

      }else{// 上传成功 获取上传文件信息

           $images = new \Think\Image();
           $images->open('./Public/upload/'.$info['Filedata']['savepath'].$info['Filedata']['savename']);
           $newsavename = str_replace('.','_thumb.',$info['Filedata']['savename']);
           $wid = 180;
           $hei = 180;
           $vv = $images->thumb($wid, $hei,\Think\Image::IMAGE_THUMB_FIXED)->save('./Public/upload/'.$info['Filedata']['savepath'].$newsavename);
           $info['Filedata']['savepath_thumb'] = "./Public/upload/".$info['Filedata']['savepath'];//缩略图显示路径
           $info['Filedata']['savethumbname_thumb'] = $newsavename;
         foreach($info as $file){
            echo   '/upload/'.$file['savepath'].$file['savethumbname_thumb'];;
             $data['url'] = "/upload/".$file['savepath'].$file['savepath_thumb'];
             $data['thumb_url'] = "/upload/".$file['savepath'].$file['savethumbname_thumb'];
           }
      
         }
 
      }


    }
    

  public function del(){
    if($_POST['name']!=""){
      $info = explode("/", $_POST['name']);
      //count($info)
      $url='./Public/upload/'.$info[count($info)-1];
        if(unlink($url)){
          $this->success("success");
        }
        else
          $this->error("unlink fail");
        }
      else
        $this->error("info is gap");
    }

    //退出登录
    public function logout(){
        session_destroy();  //清除服务器的sesion文件
        $this->redirect('Login/index');
    }


    //用户列表
    public function user_list(){
      //不要查询当前用户的信息
    $user_id  = $_SESSION['users']['user_id'];
     $list = D('Users')->where('user_id != '.$user_id)->order('last_login desc')->select();
     if($list){
      $this->assign('list',$list);
     }

    $this->display('user_list');

    }


    //添加好友
    public function add_user(){
      if(IS_POST){
        extract($_POST);
       $data['b_user_id'] = $user_id;
       $data['explain'] = trim($message);
       $data['s_user_id'] = $_SESSION['users']['user_id'];
       $data['createtime'] = date('Y-m-d H:i:s');
       //判断是否已经提交了好友申请
       $row = D('friend_apply')->where('b_user_id='.$user_id.' and s_user_id='.$_SESSION['users']['user_id'])->find();
       if($row){
         echo json_encode(array('code'=>1,'msg'=>'您已近提交了好友申请，请等待用户审核!'));exit;
       }
       $res = D('friend_apply')->add($data);
        if($res){
          echo json_encode(array('code'=>1,'msg'=>'申请成功!'));exit;
        }
      }else{
      $user_id = empty($_GET['user_id'])?"":$_GET['user_id'];
      $this->assign('user_id',$user_id);
      $this->display();
      }
    }
}
?>